<script setup>
import {
  changeorder, changepriceservice, deleteOrderanOrderdetailService,
  deletorderDetailservice, findcouponsByuseridservice,
  getamountpriceservice, getbestcouponService, getbetterpercentService,
  getordersevice, modifysalesService,
  updateorDerstatusservice,
  userorder
} from "@/api/food.js";
import {computed, h, onMounted, reactive, ref} from "vue";
const items = reactive([]);
const pageSize = 8; // 每页显示的卡片数量
const currentPage = ref(1); // 当前页数
const input = ref(0.0)
const types=ref('warning')
const title=ref('');
const showalret=ref(false);
const subject=ref('顾客')
const orderno=ref(1);
const dialogVisible = ref(false);
const activeName = ref('1')
const Discountcoupon = reactive([])
const selectvalue = ref()
let intervalId;
import { ArrowDown, ArrowUp, CircleCheck } from '@element-plus/icons-vue'
import {apipalyservice} from "@/api/apy.js";
import axios from "axios";
import {ElMessage, ElNotification} from "element-plus";
onMounted(() => {
  showOrderedItems(); // 在组件挂载时调用获取食物的方法
  getamuontprice().then(() => {
    getDiscountcoupon()
    getbestcoupon();
  });


  intervalId = setInterval(showOrderedItems, 10000000); // 每5秒执行一次
});

// 计算当前页的卡片数据
const currentPageItems = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize;
  const endIndex = startIndex + pageSize;
  return items.slice(startIndex, endIndex);
});
const handleCommentClick = () => {
  dialogVisible.value = true;

};
const handleCancel=()=>{

  dialogVisible.value = false;
}

// 计算总卡片数量
const totalItems = computed(() => items.length);

// 将卡片数据分割成每行四个的数组
const cardRows = computed(() => {
  const rows = [];
  for (let i = 0; i < currentPageItems.value.length; i += 4) {
    rows.push(currentPageItems.value.slice(i, i + 4));
  }
  return rows;
});


const showOrderedItems = async () => {
  const response =await getordersevice();
  if(response===null){
    console.log("未获取到下单信息")


  }
  else {
    items.splice(0, items.length); // 清空原有数据
    response.date.forEach(item => {
      item.ammount = 0;
      item.cardcolor=ref("green");
      item.isorder=ref(true);
      items.push(item);
      console.log(items)
    });

  }
};

const getamuontprice= async ()=>{
  const respone= await  getamountpriceservice();
  if(respone.code === 200){
    console.log("发送成功")
    await getDiscountcoupon()
    await getbestcoupon();
    input.value=respone.date;
    console.log(input.value)
  }else {
    console.log("操作计算总数失败")

  }

}

const changeprice= async (selectvalue)=>{
  const respone= await  changepriceservice(selectvalue);
  if(respone.code === 200){
    console.log("使用优惠卷成功")
    input.value=respone.date;
  }else {
    console.log("操作计算总数失败")

  }

}
const  deletorderDetail= async (foodItem) =>{
  if(foodItem!=null){
    const respone =await deletorderDetailservice(foodItem.id)
    console.log("执行成功")
  }
  else {
    console.log("id为空")
  }


}


const deleteOrderanOrderdetail = async () => {
  const response=await deleteOrderanOrderdetailService()
  if(response.code===200){
    console.log("执行成功")
    ElMessage.success("清空订单成功")
    input.value=0
    await getamuontprice();
    await showOrderedItems();
  }
  else {
    ElMessage.error("清空订单失败")
    console.log("执行失败")
  }
}

const decreaseQuantity=async (foodItem)=>{
  foodItem.ammount=-1;
  if(foodItem.quantity>0){
    const respone=await changeorder(foodItem)
    if(respone.code===200){
      console.log("执行成功")
      console.log(foodItem.quantity)
      await getamuontprice();

    }
    else {
      console.log("执行失败")
    }
  }
  else  {
    await changeorder(foodItem)
    await deletorderDetail(foodItem)
    await getamuontprice();
  }

}
const increaseQuantity=async (foodItem)=>{
  foodItem.ammount=1;
  const respone=await changeorder(foodItem)
  if(respone.code===200){
    console.log("执行成功")
    await getamuontprice();

  }
  else {
    console.log("执行失败")
  }

}


const Isselectorder=async (foodItem)=>{
  foodItem.isorder=!foodItem.isorder
if(foodItem.isorder===true){
  foodItem.cardcolor='green'
}
else {
  foodItem.cardcolor='grey'
}

}

const ConfirmOrder = async (items,selectvalue) => {
  if (items !== null && Array.isArray(items)) {
    for (let i = 0; i < items.length; i++) {
      const item = items[i];
     if(!item.isorder){
       await deletorderDetail(item);
       console.log("订单未勾选"+item.itemName)

     }
     else {
       await processItem(item);
     }
    }
  }
  if(selectvalue!=null){
    await changeprice(selectvalue)
  }
 await updateorderstatus()

}

const processItem = async (item) => {
if(item!=null){
  const  respone = await modifysalesService(item.id);
  if(respone.code===200){
    console.log("销量添加执行成功")
  }else {
    console.log("销量添加执行失败")
  }
}
  console.log(`确认订单：${item}`);
}
const updateorderstatus=async ()=>{
  const respone=await updateorDerstatusservice();
  if(respone.code===200){
    types.value='success'
    title.value='下单成功！'
    showalret.value=!showalret.value
    ElNotification({
      title: 'Title',
      message: h('i', { style: 'color: green' }, '下单成功'),
    })
    await generateOrderNumber();
    console.log(subject.value)
    await alipayorder(subject,input,orderno)
  }else {
    types.value='warning'
    ElNotification({
      title: 'Title',
      message: h('i', { style: 'color: yellow' }, '下单失败，你有账单未支付'),
    })
    title.value='下单失败，你有账单未支付！'
    showalret.value=!showalret.value

  }

}
const generateOrderNumber=()=> {
  const timestamp = Date.now().toString(); // 当前时间戳
  const randomNum = Math.floor(Math.random() * 100000).toString().padStart(5, '0'); // 5位随机数
  const orderNumber = parseInt(`${timestamp}${randomNum.toString().padStart(5, '0')}`);
 orderno.value= orderNumber; // 将生成的订单号赋值给 traceNo
}

const alipayorder=(subject,input,orderno)=>{
  const params = new URLSearchParams({
    subject: subject.value,
    traceNo: orderno.value,
    totalAmount: input.value,
  });

  window.location.href = `http://lsyspringboot.natapp1.cc/alipay/pay?${params.toString()}`;
}
const getDiscountcoupon=async ()=>{
  const respone=await findcouponsByuseridservice()
  if(respone.code===200){
    Discountcoupon.splice(0,Discountcoupon.length);
    respone.date.forEach(item=>{
      item.disabled=ref(false);
      Discountcoupon.push(item)
      console.log(Discountcoupon)
    })
    await comfimcanusecoupon(Discountcoupon);
  }

}
const comfimcanusecoupon= (Discountcoupon)=>{
 if( Discountcoupon.length>0){
   Discountcoupon.forEach(item=>{
     console.log("item.minimumSpend"+item.minimumSpend)
     console.log("input.value"+input.value)
     if(item.minimumSpend<input.value){
item.disabled=ref(false);
     }else {
       item.disabled=ref(true);
     }
   })
 }
}

const getbestcoupon = async () => {
  const response=await getbestcouponService(input.value)
  selectvalue.value=null;
  if(response.code===200){
    selectvalue.value=response.date.id;
    console.log("执行成功")
    ElMessage.success("最佳优惠卷执行成功")
  }else {
    console.log("执行失败")
    ElMessage.error("最佳优惠卷执行失败")
  }
}
</script>






<template>
  <el-alert :title="title" :type="types" center show-icon v-if="showalret" />
  <div>
    <!-- 使用 v-for 循环渲染每一页的卡片 -->
    <div v-for="(row, index) in cardRows" :key="index" class="card-row">

      <el-card
          v-for="(foodItem, foodIndex) in row"
          :key="foodIndex"
          class="card-item"
      >


        <template #header>
        <h2>{{ foodItem.itemName }}</h2>
      </template>
        <div class="card-contain">
          <el-icon :color="foodItem.cardcolor" size="30px" class="card-icon">
            <CircleCheck @click="Isselectorder(foodItem)"   class="check-icon" />
          </el-icon>
          <img :src="foodItem.imageUrl" style="width: 100%" />

        </div>

      <p class="card-price">¥: {{ foodItem.price }}</p>
      <div>
        <el-input-number  v-model="foodItem.quantity" :min="0" :max="10" :disabled="foodItem.quantity === 0"  >
          <template #decrease-icon>
            <el-icon @click="decreaseQuantity(foodItem)" >
              <ArrowDown />
            </el-icon>
          </template>
          <template #increase-icon>
            <el-icon @click="increaseQuantity(foodItem)" >
              <ArrowUp />
            </el-icon>
          </template>
        </el-input-number>
      </div>
      </el-card>
    </div>
    <el-pagination
        small
        background
        layout="prev, pager, next"
        :total="totalItems"
        :page-size="pageSize"
        v-model:currentPage="currentPage"
        class="mt-4"
    />
  </div>
  <div class="price-div">
    <el-input
        v-model="input"
        style="width: 240px"
        placeholder="Please input"
        :formatter="(value) => `总额为: ¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
        :parser="(value) => value.replace(/\$\s?|(,*)/g, '')"
        disabled
    />
    <el-button type="danger" round class="price-booton" @click="handleCommentClick()">下单</el-button>
   <el-button type="primary" round class="price-booton" @click="deleteOrderanOrderdetail()">清空下单</el-button>
  </div>
  <el-dialog
      title="提交订单"
      v-model="dialogVisible"
      width="30%"
      :before-close="handleCancel"
  >
    <el-form>
        <div class="demo-collapse">
          <el-collapse v-model="activeName" accordion>
            <el-collapse-item title="选择你要使用的优惠卷" name="1">
              <div>
                <el-select
                    v-model="selectvalue"
                    clearable
                    placeholder="Select"
                    style="width: 240px"
                >
                  <el-option
                      v-for="item in Discountcoupon"
                      :key="item.id"
                      :label="item.description"
                      :value="item.id"
                      :disabled="item.disabled"
                  />
                </el-select>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>

    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="ConfirmOrder(items,selectvalue)">确认下单</el-button>
    </span>
  </el-dialog>
</template>




<style scoped>
.card-row {
  display: flex;
  margin-bottom: 20px;
}

.card-item {
  max-width: 200px;
  margin-right: 20px;
  flex-basis: 25%;
}
.card-price{
  color: red;
}
.price-booton{
  margin-left: 200px;

}
.price-div{
  margin-top: 50px;
}
.card-icon{
  margin-right: 20px;
margin-top: 35px;
}
.card-contain{
display: flex;
align-content: center;
}
.card-icon {
  cursor: pointer;
}

.check-icon:hover {
  cursor: pointer;
}
</style>